﻿using Biz.Buffer;
using Biz.EF.Platform.SG;
using Biz.Process.Entity;
using Hjt212Parser;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Biz.Process
{
    public static class Processor2011
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(Processor2011));
        private static readonly List<string> ExistTable = new List<string>();
        /// <summary>
        ///  处理实时数据到实时数据表（一个企业一套主从套表），
        /// 企业通过企业编码区分表，多个排口数据也是放入企业一套主从套表中。
        /// </summary>
        /// <param name="content"></param>
        public static void ProcessToWechatSingleTablePerEnterprise(string content)
        {
            Log.Info("处理开始：2011->实时数据(每个企业一套实时主从表).");
            string sql = "";
            try
            {
              
                if (ProcessorHelper.IsLossInfoOfCmd(content, out var mn, out var datatime, out var port, out var codes)) return;
                if (!datatime.HasValue)
                {
                    return;
                }
                var eCode = CommonInformation.GetPollutionSourceCodeByMn(mn);
                if (string.IsNullOrWhiteSpace(eCode))
                {
                    return;
                }

                using (var pCtx = new PlatformXpfContext())
                {
                    var tableName = "主实时数据_企业ID".Replace("_企业ID", "_" + eCode);
                    int? count;
                    if (!ExistTable.Contains(tableName))
                    {
                        count = pCtx.Database.SqlQuery<int?>(Cmd2011Sqls.M_EXIST.Replace("_企业ID", "_" + eCode)).FirstOrDefault();
                        if (!count.HasValue || count < 1)
                        {
                            pCtx.Database.ExecuteSqlCommand(Cmd2011Sqls.M_CREATE.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2011Sqls.M_ALTER_1.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2011Sqls.M_ALTER_2.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2011Sqls.M_NONCLUSTERED_1.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2011Sqls.M_NONCLUSTERED_2.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2011Sqls.M_NONCLUSTERED_3.Replace("_企业ID", "_" + eCode));
                        }
                        ExistTable.Add(tableName);
                    }


                    Master master = new Master
                    {
                        enterpriseId = port.企业基本信息ID, letportId = port.ID, monitorTime = datatime.Value
                    };

                    ;
                    //todo:主污染物可以在此增加
                    if (codes.Contains("B01") || codes.Contains("w00000"))
                    {
                        master.contamTypeId = 2;
                        master.rtd = codes.Contains("B01") ? Parser.GetDoubleByKey("B01-Rtd", content) : Parser.GetDoubleByKey("w00000-Rtd", content);         
                    }
                    else if (codes.Contains("B02") || codes.Contains("a00000"))
                    {
                        master.contamTypeId = 1;
                        master.rtd = codes.Contains("B01") ? Parser.GetDoubleByKey("B02-Rtd", content) : Parser.GetDoubleByKey("a00000-Rtd", content);
                    }
                    else
                    {
                        master.contamTypeId = 2;
                        master.rtd = null;
                    }
                    //master.sum = 0;
                    var begin = new DateTime(datatime.Value.Year, datatime.Value.Month, datatime.Value.Day, datatime.Value.Hour, datatime.Value.Minute / 5 * 5, 0);
                    var end = begin.AddMinutes(5);
                    //todo:(1 == 2)可以灵活更改
                    var whereCause =
                        (1 == 2)
                        ?
                        "企业排口ID=" + port.ID + " and 监测时间>='" + begin.ToString("yyyy-MM-dd HH:mm:ss") + "' and 监测时间<'" + end.ToString("yyyy-MM-dd HH:mm:ss") + "'"
                        :
                        "企业排口ID=" + port.ID + " and 监测时间='" + datatime.Value.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                    sql = Cmd2011Sqls.M_SELECT.Replace("_企业ID", "_" + eCode).Replace("{搜索条件}", whereCause);


                    count = pCtx.Database.SqlQuery<int?>(sql).FirstOrDefault();

                    if (!count.HasValue || count < 1)
                    {
                        sql = Cmd2011Sqls.M_INSERT
                              .Replace("_企业ID", "_" + eCode)
                              .Replace("{企业排口ID}", "" + master.letportId)
                              .Replace("{监测时间}", "'" + master.monitorTime.ToString("yyyy-MM-dd HH:mm:ss") + "'")
                              .Replace("{污染物类别ID}", "" + master.contamTypeId)
                              .Replace("{RTD}", master.rtd.HasValue ? "" + master.rtd : "null")
                              .Replace("{累计量}", master.sum.HasValue ? "" + master.sum : "null");

                        pCtx.Database.ExecuteSqlCommand(sql);
                    }
                    else
                    {
                        sql = Cmd2011Sqls.M_UPDATE
                            .Replace("_企业ID", "_" + eCode)
                            .Replace("{企业排口ID}", "" + master.letportId)
                            .Replace("{监测时间}", "'" + master.monitorTime.ToString("yyyy-MM-dd HH:mm:ss") + "'")
                            .Replace("{污染物类别ID}", "" + master.contamTypeId)
                            .Replace("{RTD}", master.rtd.HasValue ? "" + master.rtd : "null")
                            .Replace("{累计量}", master.sum.HasValue ? "" + master.sum : "null")
                            .Replace("{搜索条件}", whereCause);

                        pCtx.Database.ExecuteSqlCommand(sql);
                    }
                    sql = Cmd2011Sqls.M_SELECT.Replace("_企业ID", "_" + eCode).Replace("{搜索条件}", whereCause).Replace("COUNT(1)", "ID");

                    var masterId = pCtx.Database.SqlQuery<int?>(sql).FirstOrDefault();
                    if (!masterId.HasValue)
                    {
                        return;
                    }

                    ProcessorHelper.RemoveMasterFactor(codes, true);

                    tableName = "从实时数据_企业ID".Replace("_企业ID", "_" + eCode);
                    if (!ExistTable.Contains(tableName))
                    {
                        count = pCtx.Database.SqlQuery<int?>(Cmd2011Sqls.D_EXIST.Replace("_企业ID", "_" + eCode)).FirstOrDefault();
                        if (!count.HasValue || count < 1)
                        {
                            pCtx.Database.ExecuteSqlCommand(Cmd2011Sqls.D_CREATE.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2011Sqls.D_ALTER_1.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2011Sqls.D_ALTER_2.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2011Sqls.D_NONCLUSTERED_1.Replace("_企业ID", "_" + eCode));
                            pCtx.Database.ExecuteSqlCommand(Cmd2011Sqls.D_NONCLUSTERED_2.Replace("_企业ID", "_" + eCode));
                        }
                        ExistTable.Add(tableName);
                    }
                    Slave slave = new Slave();
                    slave.masterId = masterId.Value;

                    foreach (var code in codes)
                    {
                        var contam = CommonInformation.GetContamCode(code);
                        if (contam == null)
                        {
                            continue;
                        }

                        slave.contamId = contam.ID;
                        var rtd = Parser.GetDoubleByKey(code + "-Rtd", content);
                        slave.rtd = rtd.HasValue ? rtd.Value : 0;
                        slave.zsRtd = Parser.GetDoubleByKey(code + "-ZsRtd", content);
                        slave.flag = Parser.GetStringByKey(code + "-Flag", content);
                        whereCause = "主实时数据ID=" + slave.masterId + " and 污染物编码ID=" + slave.contamId;
                        sql = Cmd2011Sqls.D_SELECT.Replace("_企业ID", "_" + eCode).Replace("{搜索条件}", whereCause);

                        count = pCtx.Database.SqlQuery<int?>(sql).FirstOrDefault();
                        if (!count.HasValue || count < 1)
                        {
                            sql = Cmd2011Sqls.D_INSERT
                                  .Replace("_企业ID", "_" + eCode)
                                  .Replace("{主实时数据ID}", "" + slave.masterId)
                                  .Replace("{污染物编码ID}", "" + slave.contamId)
                                  .Replace("{RTD}", "" + slave.rtd)
                                  .Replace("{ZSRTD}", slave.zsRtd.HasValue ? "" + slave.rtd : "null")
                                  .Replace("{Flag}", string.IsNullOrWhiteSpace(slave.flag) ? "null" : "'" + slave.flag + "'");

                            pCtx.Database.ExecuteSqlCommand(sql);
                        }
                        else
                        {
                            sql = Cmd2011Sqls.D_UPDATE
                                .Replace("_企业ID", "_" + eCode)
                                .Replace("{主实时数据ID}", "" + slave.masterId)
                                .Replace("{污染物编码ID}", "" + slave.contamId)
                                .Replace("{RTD}", "" + slave.rtd)
                                .Replace("{ZSRTD}", slave.zsRtd.HasValue ? "" + slave.rtd : "null")
                                .Replace("{Flag}", string.IsNullOrWhiteSpace(slave.flag) ? "null" : "'" + slave.flag + "'")
                                .Replace("{搜索条件}", whereCause);

                            pCtx.Database.ExecuteSqlCommand(sql);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(sql + Environment.NewLine + ex + Environment.NewLine + content);
            }
            Log.Info("处理结束：2011->实时数据(每个企业一套实时主从表).");
        }
        /// <summary>
        /// 处理实时数据到实时数据表（主从套表）
        /// </summary>
        /// <param name="content"></param>
        public static void ProcessToCommonTable(string content)
        {
            Log.Info("处理开始：2011->实时数据(所有企业一套实时主从表).");
            try
            {
                if (ProcessorHelper.IsLossInfoOfCmd(content, out var mn, out var datatime, out var port, out var codes)) return;

                if (!datatime.HasValue)
                {
                    return;
                }
                using (var contextTarget = new PlatformXpfContext())
                {
                    var master = contextTarget.主实时数据
                        .Where(t => t.企业排口ID == port.ID).FirstOrDefault(t => t.监测时间.Equals(datatime.Value));
                    if(master!=null) return;
                     master = new 主实时数据
                    {
                        企业基本信息ID = port.企业基本信息ID,
                        企业排口ID = port.ID,
                        监测时间 = datatime.Value
                    };
                    contextTarget.主实时数据.Add(master);


                    if (codes.Contains("B01") || codes.Contains("w00000"))
                    {
                        master.污染物类别ID = 2;
                        master.RTD = codes.Contains("B01") ? Parser.GetDoubleByKey("B01-Rtd", content) : Parser.GetDoubleByKey("w00000-Rtd", content);
                        master.累计量 = codes.Contains("B01") ? Parser.GetDecimalByKey("B01-Cou", content) : Parser.GetDecimalByKey("w00000-Cou", content);

                    }
                    else if (codes.Contains("B02") || codes.Contains("a00000"))
                    {
                        master.污染物类别ID = 1;
                        master.RTD = codes.Contains("B02") ? Parser.GetDoubleByKey("B02-Rtd", content) : Parser.GetDoubleByKey("a00000-Rtd", content);
                        master.累计量 = codes.Contains("B02") ? Parser.GetDecimalByKey("B02-Cou", content) : Parser.GetDecimalByKey("a00000-Cou", content);

                    }
                    else
                    {
                        master.污染物类别ID = 2;
                        master.RTD = null;
                        master.累计量 = null;

                    }
                    foreach (var detailCode in codes)
                    {
                        if (ProcessorHelper.IsMasterCode(detailCode))
                        {
                            continue;
                        }
                      var  pollutionInfo =CommonInformation.GetContamCode(detailCode);
                      if (pollutionInfo == null)
                      {
                          Log.Warn("没有对应污染物信息:"+detailCode);
                          continue;
                      }
                       var rtdDouble = Parser.GetDoubleByKey(detailCode + "-Rtd", content);
                       if (rtdDouble == null)
                       {
                           Log.Warn("对应污染物 " + detailCode+" 没有实时值.");
                            continue;
                       }

                        var detail = new 从实时数据
                        {
                            污染物编码ID = pollutionInfo.ID,
                            RTD = rtdDouble.Value,
                            ZSRTD = Parser.GetDoubleByKey(detailCode + "-ZsRtd", content),
                            Flag = Parser.GetStringByKey(detailCode + "-Flag", content)
                        };
                        master.从实时数据.Add(detail);
                    }
                    contextTarget.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex + Environment.NewLine + content);
            }
            Log.Info("处理结束：2011->实时数据(所有企业一套实时主从表).");
        }
        /// <summary>
        /// 处理实时数据到实时监控表（主从套表）
        /// </summary>
        /// <param name="content"></param>
        public static void ProcessToMonitorTable(string content)
        {
            Log.Info("处理开始：2011->实时监控表(所有企业一套实时主从表).");
            try
            {
                if (ProcessorHelper.IsLossInfoOfCmd(content, out var mn, out var datatime, out var port, out var codes))
                {
                    return;
                }

                using (var pCtx = new PlatformXpfContext())
                {

                    var masterMonitor = pCtx.主实时监控
                        .Where(t => t.企业基本信息ID == port.企业基本信息ID)
                        .FirstOrDefault(t => t.企业排口ID == port.ID);
                    if (masterMonitor == null)
                    {
                        masterMonitor = new 主实时监控
                        {
                            企业基本信息ID = port.企业基本信息ID,
                            企业排口ID = port.ID
                        };
                        pCtx.主实时监控.Add(masterMonitor);
                    }

                    if (masterMonitor.实时数据时间.HasValue && masterMonitor.实时数据时间.Value > datatime.Value)
                    {
                        Log.Warn("无须处理：监控表时间新" + masterMonitor.实时数据时间.Value + "：\r\n" + content);
                        return;
                    }
                    if (codes.Contains("B01") || codes.Contains("w00000"))
                    {
                        masterMonitor.污染物类别ID = 2;
                        var rtd = codes.Contains("B01") ? Parser.GetDoubleByKey("B01-Rtd", content) : Parser.GetDoubleByKey("w00000-Rtd", content);
                        masterMonitor.瞬时量 = rtd;
                    }
                    else if (codes.Contains("B02") || codes.Contains("a00000"))
                    {
                        masterMonitor.污染物类别ID = 1;
                        var rtd = codes.Contains("B02") ? Parser.GetDoubleByKey("B02-Rtd", content) : Parser.GetDoubleByKey("a00000-Rtd", content);
                        masterMonitor.瞬时量 = rtd;
                    }
                    else
                    {
                        masterMonitor.污染物类别ID = 2;
                    }
                    masterMonitor.实时数据时间 = datatime;
                    masterMonitor.在线状态ID = 1201;
                    masterMonitor.在线状态时间 = DateTime.Now;
                    pCtx.SaveChanges();

                    ProcessorHelper.RemoveMasterFactor(codes, true);

                    foreach (var code in codes)
                    {
                        var contam = CommonInformation.GetContamCode(code);
                        if (contam == null)
                        {
                            continue;
                        }
                        var detailMonitor = masterMonitor.从实时监控.FirstOrDefault(t => t.污染物编码ID == contam.ID);
                        if (detailMonitor == null)
                        {
                            detailMonitor = new 从实时监控
                            {
                                污染物编码ID = contam.ID
                            };
                            masterMonitor.从实时监控.Add(detailMonitor);
                        }
                        var v = Parser.GetDoubleByKey(code + "-Rtd", content);
                        detailMonitor.瞬时量 = v ?? 0;
                    }
                    pCtx.SaveChanges();

                }
            }
            catch (Exception ex)
            {
                Log.Error(ex + Environment.NewLine + content);
            }
            Log.Info("处理结束：2011->实时监控表(所有企业一套实时主从表).");

        }

    }
}
